import asyncio
import logging
import os
import tempfile
from typing import Dict, List, Optional
from app.core.config import settings
from app.services.storage_service import storage_service

logger = logging.getLogger(__name__)


class PlaywrightService:
    """Playwright自动化服务"""
    
    def __init__(self):
        self.headless = settings.PLAYWRIGHT_HEADLESS
        self.timeout = settings.PLAYWRIGHT_TIMEOUT
    
    async def execute_publish(self, post_data: Dict) -> Dict[str, any]:
        """执行发布任务"""
        try:
            # 1. 准备发布数据
            prepared_data = await self._prepare_publish_data(post_data)
            if not prepared_data:
                return {"success": False, "message": "Failed to prepare publish data"}
            
            # 2. 动态导入并执行发布脚本
            try:
                from scripts.publish_post import run as run_publish_script
                result = await run_publish_script(prepared_data)
                
                # 3. 清理临时文件
                await self._cleanup_temp_files(prepared_data.get('temp_files', []))
                
                return result
                
            except ImportError:
                logger.error("Publish script not found. Creating mock implementation.")
                # 如果脚本不存在，返回模拟结果
                await asyncio.sleep(2)  # 模拟执行时间
                return {
                    "success": True, 
                    "message": "Mock publish completed",
                    "post_url": "https://www.xiaohongshu.com/explore/mock_post_id"
                }
                
        except Exception as e:
            logger.error(f"Error executing publish: {e}")
            return {"success": False, "message": str(e)}
    
    async def _prepare_publish_data(self, post_data: Dict) -> Optional[Dict]:
        """准备发布数据，包括下载图片到本地"""
        try:
            prepared_data = {
                "title": post_data.get("title", ""),
                "content": post_data.get("content", ""),
                "tags": post_data.get("tags", ""),
                "images": [],
                "temp_files": [],
                "config": {
                    "headless": self.headless,
                    "timeout": self.timeout
                }
            }
            
            # 下载图片到临时目录
            images = post_data.get("images", [])
            if images:
                temp_dir = tempfile.mkdtemp(prefix="xiaohongshu_")
                
                for i, image_url in enumerate(images):
                    if image_url.startswith('http'):
                        # 如果是完整URL，直接使用
                        prepared_data["images"].append(image_url)
                    else:
                        # 如果是对象存储路径，下载到本地
                        temp_file_path = os.path.join(temp_dir, f"image_{i}.jpg")
                        
                        if storage_service.download_file(image_url, temp_file_path):
                            prepared_data["images"].append(temp_file_path)
                            prepared_data["temp_files"].append(temp_file_path)
                        else:
                            logger.warning(f"Failed to download image: {image_url}")
            
            return prepared_data
            
        except Exception as e:
            logger.error(f"Error preparing publish data: {e}")
            return None
    
    async def _cleanup_temp_files(self, temp_files: List[str]):
        """清理临时文件"""
        for file_path in temp_files:
            try:
                if os.path.exists(file_path):
                    os.remove(file_path)
                    logger.debug(f"Cleaned up temp file: {file_path}")
            except Exception as e:
                logger.warning(f"Failed to cleanup temp file {file_path}: {e}")
        
        # 清理临时目录
        if temp_files:
            try:
                temp_dir = os.path.dirname(temp_files[0])
                if os.path.exists(temp_dir) and os.path.basename(temp_dir).startswith('xiaohongshu_'):
                    os.rmdir(temp_dir)
                    logger.debug(f"Cleaned up temp directory: {temp_dir}")
            except Exception as e:
                logger.warning(f"Failed to cleanup temp directory: {e}")
    
    async def test_browser(self) -> Dict[str, any]:
        """测试浏览器环境"""
        try:
            from playwright.async_api import async_playwright
            
            async with async_playwright() as p:
                # 使用Firefox浏览器进行测试，与小红书服务保持一致
                browser = await p.firefox.launch(headless=self.headless)
                page = await browser.new_page()
                
                # 访问测试页面
                await page.goto("https://www.baidu.com", timeout=self.timeout)
                title = await page.title()
                
                await browser.close()
                
                return {
                    "success": True,
                    "message": f"Firefox browser test successful. Page title: {title}",
                    "browser_version": p.firefox.name
                }
                
        except ImportError:
            return {
                "success": False,
                "message": "Playwright not installed. Run: pip install playwright && playwright install"
            }
        except Exception as e:
            return {
                "success": False,
                "message": f"Firefox browser test failed: {e}"
            }
    
    def validate_post_data(self, post_data: Dict) -> Dict[str, any]:
        """验证发布数据"""
        errors = []
        
        # 检查必需字段
        if not post_data.get("title"):
            errors.append("Title is required")
        
        if not post_data.get("content"):
            errors.append("Content is required")
        
        # 检查标题长度
        title = post_data.get("title", "")
        if len(title) > 30:
            errors.append("Title too long (max 30 characters)")
        
        # 检查内容长度
        content = post_data.get("content", "")
        if len(content) > 1000:
            errors.append("Content too long (max 1000 characters)")
        
        # 检查图片数量
        images = post_data.get("images", [])
        if len(images) > 9:
            errors.append("Too many images (max 9 images)")
        
        if errors:
            return {
                "valid": False,
                "errors": errors
            }
        
        return {
            "valid": True,
            "message": "Post data is valid"
        }


# 创建全局实例
playwright_service = PlaywrightService()